/*
 * @Author: malgee
 * @Date: 2025-04-27 09:34:38
 * @LastEditors: maling
 * @LastEditTime: 2025-04-27 13:22:38
 * @FilePath: /vue3-ts-cms/src/utils/map-menus.ts
 * @Description: 
 * 
 */
import { type IBreadcrumb } from '@/base-ui/breadcrumb'
import { RouteRecordRaw } from 'vue-router'

let firstMenu: any = null
/**
 * 根据用户菜单加载动态路由
 * @param menus 用户菜单
 * @returns 动态路由
 */
export const loadDynamicRoutes = (menus: any[]) => {
  const userDynamicRoutes:  RouteRecordRaw[] = []
  
  // 1. 先加载所有动态路由
  const allDynamicRoutes: RouteRecordRaw[] = []
  const routeFiles = require.context('@/router/main', true, /\.ts$/)
  routeFiles.keys().forEach(key => {
    const route = require('@/router/main' + key.split('.')[1])
    allDynamicRoutes.push(route.default)
  })

  // 2. 根据菜单匹配动态路由
  const _recurseGetMenus = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allDynamicRoutes.find(route => route.path === menu.url)
        if (route) userDynamicRoutes.push(route)
        if (!firstMenu) firstMenu = menu
      } else {
        _recurseGetMenus(menu.children)
      }
    }
  }

  _recurseGetMenus(menus)
  return userDynamicRoutes
} 

/**
 * 获取面包屑所有菜单路径
 * @param menus 菜单列表
 * @param currentPath 当前路径
 * @returns 面包屑路径
 */
export const mapMenusToRoutes = (menus: any[], currentPath: string): IBreadcrumb[] => {
  const breadcrumbs: IBreadcrumb[] = []
  pathMapToMenu(menus, currentPath, breadcrumbs)
  return breadcrumbs
}


export const pathMapToMenu = (menus: any[], currentPath: string, breadcrumbs?: IBreadcrumb[]): any => {
  for (const menu of menus) {
   if (menu.type === 1) {
    const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
    if (findMenu) {
      breadcrumbs?.push({ name: menu.name })
      breadcrumbs?.push({ name: findMenu.name })
      return findMenu
    }
   } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
   }
  }
}


export const mapMenusToPermissions = (menus: any[]): string[] => {
  const permissions: string[] = []
  const _recurseGetPermissions = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermissions(menu.children ?? [])
      } else {  // === 3 才是按钮权限 eg: system:user:add
        permissions.push(menu.permission)
      }
    }
  }
  _recurseGetPermissions(menus)
  return permissions
}

export { firstMenu }